package com.app.test.leak;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

/**
 * toast显示工具类-用于内存泄漏测试
 *
 * @author lucher
 * @since 2023-05-27
 */
public class ToastUtil {

    private static Toast toast;
    private static Handler handler = new Handler();

    /**
     * 显示toast
     *
     * @param context
     * @param text
     */
    public static void show(Context context, String text) {
        handler.post(() -> {
            if (toast != null) {
                toast.cancel();
            }
            try {
                //为了更容易模拟并发调用实例化多个toast导致内存泄漏，此处睡眠1s
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d("LeakTest", "make text thread :" + Thread.currentThread().getName());
            toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
            toast.show();
        });
    }
}
